package com.jwater.core.manager.common;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.jwater.core.utils.SysType;
import com.jwater.launch.HomePath;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jwater.core.manager.common.model.JvmInfo;
import com.jwater.core.utils.ProcessUtils;

/**
 * @description: 获取本机所有的java进程信息
 * @author: jnner
 * @createDate: 2021/2/5
 * @version: 1.0
 */
public class JvmUtils {
    protected static Logger logger = LoggerFactory.getLogger(JvmUtils.class);

    public static List<JvmInfo> listJvm() {
        List<JvmInfo> jvmInfos = new ArrayList<>();
        try {
            List<String> lines = ProcessUtils.cmd(null, "jps -mlv");
            for (String line : lines) {
                if (line.indexOf("sun.tools.jps.Jps") > -1) {
                    continue;
                }
                int index = line.indexOf(" ");
                String pid = line.substring(0, index);
                String params = line.substring(index + 1);
                JvmInfo jvmInfo = new JvmInfo();
                jvmInfo.setPid(pid);
                jvmInfo.setParams(params.trim());
                jvmInfos.add(jvmInfo);
            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return jvmInfos;
    }

    public static String cmdJvm(String cmdType, int pid) {
        try {
            File dir = new File(HomePath.getTmpFilePath());
            if (!dir.exists()) {
                dir.mkdirs();
            }
            String dst = HomePath.getTmpFilePath() + UUID.randomUUID().toString();
            String cmd = null;
            if ("jinfo".equals(cmdType)) {
                cmd = "jinfo " + pid + " >" + dst;
            } else if ("jstat".equals(cmdType)) {
                cmd = "jstat -gc " + pid + " >" + dst;
            } else if ("jstack".equals(cmdType)) {
                cmd = "jstack " + pid + " >" + dst;
            } else if ("jmap".equals(cmdType)) {
                cmd = "jmap -dump:format=b,file=" + dst + " " + pid;
            }
            if (cmd != null) {
                String sysType = SysType.getSysType();
                if (SysType.WINDOWS.equals(sysType)) {
                    ProcessUtils.exeCmd(null, cmd, null).process.waitFor();
                } else if (SysType.LINUX.equals(sysType)) {
                    ProcessUtils.exeCmd(new String[]{"sh", "-c", cmd}, null, null).process.waitFor();
                }
            }
            if (new File(dst).exists()) {
                return dst;
            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return null;
    }

}
